package rt.wxf_bo.ja;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.UnitValue;

import java.io.FileInputStream;
import java.io.IOException;

public class ExcelToPdf {
    public static void main(String[] args) {
        try {
            // 读取Excel文件
            FileInputStream fis = new FileInputStream("D:\\pdf\\to\\4.7测试业务员4的客户01-2024-04-07报价单.xls");
            Workbook workbook = new HSSFWorkbook(fis);
            Sheet sheet = workbook.getSheetAt(0);

            // 创建PDF文件
            PdfWriter writer = new PdfWriter("D:\\pdf\\to\\47测试业务员4的客户0120240407101311.pdf");
            PdfDocument pdf = new PdfDocument(writer);
            Document document = new Document(pdf);

            // 获取Excel表格的列数
            int numColumns = sheet.getRow(0).getPhysicalNumberOfCells();

            // 创建PDF表格，设置列宽
            Table table = new Table(UnitValue.createPercentArray(numColumns)).useAllAvailableWidth();

            // 遍历Excel中的每一行
            for (Row row : sheet) {
                // 遍历Excel中的每一列
                for (int i = 0; i < numColumns; i++) {
                    org.apache.poi.ss.usermodel.Cell excelCell = row.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                    String cellValue = getCellValueAsString(excelCell);

                    // 创建iText的Cell对象，并将Excel单元格的值添加到PDF表格中
                    Cell pdfCell = new Cell().add(new Paragraph(cellValue));
                    table.addCell(pdfCell);
                }
            }

            // 将表格添加到PDF文档
            document.add(table);

            // 关闭文档
            document.close();
            workbook.close();
            fis.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将Excel单元格的值转换为字符串
     */
    private static String getCellValueAsString(org.apache.poi.ss.usermodel.Cell cell) {
        if (cell == null) {
            return "";
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return String.valueOf(cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            case BLANK:
                return "";
            default:
                return "";
        }
    }
}